package app.view.mediators
{
	import app.AppConstants;
	import app.view.forms.AddStateForm;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.controls.Button;
	import mx.events.FlexEvent;
	
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;

	public class AddStateFormMediator extends Mediator
	{
		public static const NAME:String = "AddStateMediator"
		public function AddStateFormMediator()	{
			super(NAME, new AddStateForm());
		}
		
		override public function onRegister():void{
			attachView();
			initiate();	
		}
		
		public function set packageList(list:Array):void{
			view.pkgCombo.sharedDataProvider = list;
		}
		
		private function initiate():void{
			view.addEventListener(MouseEvent.CLICK, onClick);
			view.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
		}
		
		private function attachView():void{
			sendNotification(AppConstants.ATTACH_TO_APP_DISPLAY, view);
		}
		
		override public function onRemove():void{
			removeListeners();		
		}
		
		private function onCreationComplete(event:FlexEvent):void{
			view.removeEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
			//view.pkgCombo.dataProvider = PackageProxy(facade.retrieveProxy(PackageProxy.NAME)).packages;
			activate();
		}
		
		private function onClick(event:MouseEvent):void{
			var target:Button = event.target as Button;
			if(!target)return
			switch(event.target.id){
				case"plusButton":
					toggleViewState();
					break;
			}
		}
		
		private function toggleViewState():void{
			if(view.currentState == "expanded"){
				deactivate();
				view.currentState = "contracted";
			}else{
				activate();
				view.currentState = "expanded";
			}
		}
		
		private function activate():void{
			addListeners();
		}
		
		private function deactivate():void{
			removeListeners();
		}
		
		private function addListeners():void{
			view.input.addEventListener(FlexEvent.ENTER, onCommit);
		}
		
		private function removeListeners():void{
			view.removeEventListener(FlexEvent.ENTER, onCommit);
		}
		
		
		
		private function onCommit( event:Event ):void{
			sendCreateState();
			view.input.text = "";
		}
		
		private function sendCreateState():void{
			view.pkgCombo.addTextToList();
			sendNotification( AppConstants.CREATE_NEW_STATE, view.pkgCombo.text, view.input.text )
		}
		
		private function get view():AddStateForm{
			return AddStateForm(viewComponent);
		}
		
	}
}